package com.zjdiepu.www.biz;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.enums.type.AttachmentSort;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.biz.ibiz.IFileHelpService;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.common.util.FileUtil;
import com.zjdiepu.www.common.util.StringUtil;
import com.zjdiepu.www.common.util.UUIDFactory;
import com.zjdiepu.www.config.FileProperty;
import com.zjdiepu.www.dao.base.OtherAttachmentsMapper;
import com.zjdiepu.www.model.base.dto.OtherAttachments;
import com.zjdiepu.www.util.CachedEnums;
/**
 * 项目名称：dpqc-parent-manager-file <br/> 
 * 类名称：FilePathServiceImpl <br/>  
 * 类描述：文件路径操作<br/>    
 * 创建人：xiongxiaotun <br/> 
 * 创建时间：2017年4月12日 下午3:09:01  <br/>   
 * 修改人：xiongxiaotun <br/> 
 * 修改时间：2017年4月12日 下午3:09:01   <br/>  
 * 修改备注：    <br/> 
 * @version V1.0   <br/>
 */
@Service
public class FileHelpServiceImpl implements IFileHelpService {
	private static final Logger logger = LoggerFactory.getLogger(FileHelpServiceImpl.class);
	
	@Autowired
	private FileProperty fileProperty;
	@Autowired
	private OtherAttachmentsMapper otherAttachmentsMapper;
	
	@Override
	public ApiResponse saveToFile(MultipartFile uploadFile, String currentUserId, String currentUserName, 
			String savePath, String modeId,boolean flag,String cusId) {
		try {
			long size = uploadFile.getSize();
			if(size == 0) {
				return  ApiResponse.fail(ResultFlagType.FILE_NOT_SELECTED);
			}
			OtherAttachments otherAttachments = saveLocal(uploadFile, currentUserId, currentUserName, savePath, modeId,flag,cusId);
			Map<String, String> result = new HashMap<String, String>();
			result.put("name", otherAttachments.getFileShowName()); //表单名称
			result.put("fileId", otherAttachments.getId());
			result.put("path", savePath);
			otherAttachmentsMapper.insert(otherAttachments);
			return ApiResponse.success(result);
		} catch (IOException e) {
			logger.debug("upload file exception.", e);
			return ApiResponse.fail(ResultFlagType.FILE_UPLOAD_FAIL);
		}
	}

	@Override
	public ApiResponse saveBatchToFiles(List<MultipartFile> uploadFiles, String currentUserId, String currentUserName,
			String savePath, String modeId,boolean flag,String cusId) {
		try {
			if(CollectionUtils.isEmpty(uploadFiles)) {
				return ApiResponse.fail(ResultFlagType.FILE_NOT_SELECTED);
			}
			List<OtherAttachments> otherAttachmentss = new ArrayList<OtherAttachments>();
			List<Map<String, String>> results = new ArrayList<Map<String,String>>();
			for(MultipartFile uploadFile : uploadFiles) {
				OtherAttachments otherAttachments = saveLocal(uploadFile, currentUserId, currentUserName, savePath, modeId,flag,cusId);
				Map<String, String> result = new HashMap<String, String>();
				result.put("name", uploadFile.getName()); //表单名称
				result.put("fileId", otherAttachments.getId());
				result.put("path", savePath);
				otherAttachmentss.add(otherAttachments);
			}
			otherAttachmentsMapper.insertBatch(otherAttachmentss);
			return ApiResponse.success(results);
		} catch (IOException e) {
			logger.debug("upload file exception.", e);
			return ApiResponse.fail(ResultFlagType.FILE_UPLOAD_FAIL);
		}
	}
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: pregressForSave  <br/>
	 * @Description:  保存到本地 <br/>
	 * @param uploadFile
	 * @param currentUserId
	 * @param currentUserName
	 * @param savePath
	 * @param modeId
	 * @return
	 * @throws IOException
	 * @version V1.0  <br/>
	 */
	private OtherAttachments saveLocal(MultipartFile uploadFile, String currentUserId, String currentUserName,
			String savePath, String modeId,boolean flag,String cusId) throws IOException	{
		String uuid = UUIDFactory.getUUID();
		//后缀
		String name = uploadFile.getOriginalFilename();
		String fileSuffix = FileUtil.getFileSuffix(name);
		String tempName = uuid + StringUtil.PERIOD + fileSuffix;
		savePath = savePath + tempName;
		
		OtherAttachments otherAttachments = new OtherAttachments();
		otherAttachments.initInsertData(currentUserId, currentUserName);
		otherAttachments.setModeId(modeId);
		otherAttachments.setLocalFilePath(savePath);
		otherAttachments.setOssPath(savePath);
		otherAttachments.setFileSize((int)uploadFile.getSize());
		otherAttachments.setFileName(tempName);
		otherAttachments.setFileShowName(name);
		otherAttachments.setFileHandleStatus("01");
		otherAttachments.setCustomerId(cusId);
		URL xmlpath = this.getClass().getClassLoader().getResource("");
		String pathTo="";
        pathTo=String.valueOf(xmlpath)+new String(fileProperty.getUploadPath().getBytes("ISO-8859-1"),"UTF-8");
        if(pathTo.contains("file:/")){
        	pathTo=pathTo.substring(6,pathTo.length());
        }
		String realPath= pathTo + savePath;
		if(flag==true){
			realPath=pathTo+name;
		}
		 
		FileUtils.copyInputStreamToFile(uploadFile.getInputStream(), new File(realPath));
		return otherAttachments;
	}
	
	@Override
	public String getPathFromType(Integer fileType) {
		AttachmentSort fileBussinuessType = CachedEnums.getByCode(fileType, AttachmentSort.class);
		if(null == fileBussinuessType) {
			fileBussinuessType = AttachmentSort.MO_REN_LEI_XING;
		}
		String path = DateUtil.dateTo8Str(new Date()) + "/";
		switch (fileBussinuessType) {
		case MO_REN_LEI_XING: //默认路径
			path = fileProperty.getMoRenLeiXing();
			break;
		case YONG_HU_TOU_XIANG: //用户头像
			path = fileProperty.getYongHuTouXiang();
			break;
		case SHEN_FEN_ZHENG_MING: //身份证明
			path = fileProperty.getShenFenZhengMing();
			break;
		case ZHONG_YAO_YUAN_JIAN://重要原件
			path = fileProperty.getZhongYaoYuanJian();
			break;
		case JU_ZHU_ZHENG_MING://居住证明
			path = fileProperty.getJuZhuZhengMing();
			break;
		case YIN_HANG_LIU_SHUI://银行流水
			path = fileProperty.getYinHangLiuShui();
			break;
		case ZHU_JIE_REN_QIAN_ZI://主借人签字
			path = fileProperty.getZhuJieRenQianZi();
			break;
		case PEI_OU_QIAN_ZI://配偶签字
			path = fileProperty.getPeiOuQianZi();
			break;
		case DAN_WEI_FANG://单位访
			path = fileProperty.getDanWeiFang();
			break;
		case JIA_FANG://家访
			path = fileProperty.getJiaFang();
			break;
		case YING_YE_ZHI_ZHAO://营业执照
			path = fileProperty.getYingYeZhiZhao();
			break;
		case GONG_SI_LIU_SHUI://公司流水
			path = fileProperty.getGongSiLiuShui();
			break;
		case YAN_ZI_BAO_GAO://验资报告
			path = fileProperty.getYanZiBaoGao();
			break;
		case KAI_KA_ZI_LIAO://开卡资料
			path = fileProperty.getKaiKaZiLiao();
			break;
		case TI_CHE_ZI_LIAO://提车资料
			path = fileProperty.getKaiKaZiLiao();
			break;
		case QI_TA_ZI_LIAO_ZHAO_PIAN://其它资料照片
			path = fileProperty.getKaiKaZiLiao();
			break;
		case QI_TA_ZI_LIAO_SHI_PIN://其它资料视频
			path = fileProperty.getKaiKaZiLiao();
			break;
		default:
			path = fileProperty.getMoRenLeiXing();
			break;
		}
		return path;
	}
	
	@Override
	public ResultFlagType checkPath(MultipartFile file, Integer imageType) {
		if(null == file) {
			 return ResultFlagType.PARAM_EMPTY;
		} 
		AttachmentSort fileBussinuessType = CachedEnums.getByCode(imageType, AttachmentSort.class);
		if(null == fileBussinuessType) {
			return  ResultFlagType.FILE_BUSSINESS_TYPE_NOT_FOUND;
		}
		return ResultFlagType.SUCCESS;
	}

	@Override
	public ResultFlagType checkPath(
			MultipartHttpServletRequest multipartRequest, Integer imageType) {
		if(null == multipartRequest) {
			 return ResultFlagType.PARAM_EMPTY;
		} 
		AttachmentSort fileBussinuessType = CachedEnums.getByCode(imageType, AttachmentSort.class);
		if(null == fileBussinuessType) {
			return  ResultFlagType.FILE_BUSSINESS_TYPE_NOT_FOUND;
		}
		return ResultFlagType.SUCCESS;
	}
}
